var ue = UE.getEditor('myEditor', {
    toolbars: [
        [
            'fullscreen', //全屏
            'undo', //撤销
            'redo', //重做
            'bold', //加粗
            'italic', //斜体
            'underline', //下划线
            'indent', //首行缩进
            'fontfamily', //字体
            'fontsize', //字号
            'paragraph', //段落格式
            'forecolor', //字体颜色
            'backcolor', //背景色
            'justifyleft', //居左对齐
            'justifycenter', //居中对齐
            'justifyright', //居右对齐
            'removeformat', //清除格式
            'link', //超链接
            'unlink', //取消链接
            'lineheight', //行间距
            'horizontal', //分隔线
            'simpleupload', //单图上传
            // 'spechars', //特殊字符
            // 'searchreplace', //查询替换
            'preview', //预览
            'cleardoc', //清空文档

        ]
    ],
    //focus时自动清空初始化时的内容
    autoClearinitialContent: true,
    //关闭字数统计
    wordCount: false,
    //关闭elementPath
    elementPathEnabled: false,
    //默认的编辑区域高度
    initialFrameHeight: 280,
    // 防止div赋值到编辑器变成P
    allowDivTransToP: false,
    //是否自动保存
    enableAutoSave: false,
    // 是否自动长高,默认true
    autoHeightEnabled: false
        //是否保持toolbar的位置不动,默认true
        // autoFloatEnabled:false
        //浮动时工具栏距离浏览器顶部的高度，用于某些具有固定头部的页面
        // topOffset:30
        //编辑器底部距离工具栏高度(如果参数大于等于编辑器高度，则设置无效)
        //,toolbarTopOffset:400
        //更多其他参数，请参考ueditor.config.js中的配置项
})

var articleId;
var ueditorContent;

function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg); //匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; //返回参数值
}

function errorPrecess(ret) {

    if (ret.code == -1) {
        location.href = "login.html";
    } else {
        alert(ret.message);
    }
}

$(function() {
    var winHeight = $(window).height();
    $(".content-wrapper").css("minHeight", winHeight - 52);



    var wrapper = new Vue({
        el: '.wrapper',
        data: {
            article: {
                id: 0,
                title: '',
                headImg: '',
                content: '',
                type: '',
                createTime: ''
            }

        },
        components: {
            mainHead,
            mainSidebar
        },
        methods: {
            addImg: function() {
                $("#btnAddImg").click();
            },
            uploadImg: function() {

                var files = $("#btnAddImg").get(0).files[0];
                if (files == undefined) {
                    alert("请选择图片！");
                    return;
                }
                var form = new FormData();
                form.append("file", files);
                $.ajax({
                    url: "../article/uploadImg?id=" + this.article.id,
                    type: "POST",
                    data: form,
                    async: true,
                    processData: false,
                    contentType: false,
                    success: function(ret) {
                        console.log("tupian");
                        console.log(ret);

                        if (ret.code == 0) {
                            // var imgsrc=".."+ret.data.headImg;  
                            wrapper.$set(wrapper.article, "headImg", ret.data.headImg);
                            wrapper.$set(wrapper.article, "mediaId", ret.data.mediaId);
                            wrapper.$set(wrapper.article, "id", ret.data.id);

                            // 更新微信分享图片
                            /*wx.ready(function(){
                                share();
                            });*/
                        } else {
                            errorPrecess(ret);
                        }

                    }
                });

            },
            save: function() {
                // checkLogin();
                this.article.content = ue.getContent();

                if ((this.article.title == '') || (this.article.headImg == '') || (this.article.content == '')) {
                    alert("标题,内容,封面图片,全部为必填项,请填写完整!");
                    return false;

                }

                console.log("all");
                console.log(this.article);
                $.ajax({
                    type: 'POST',
                    url: '../article/save',
                    contentType: 'application/json',
                    //data:{username:username, password:password},
                    data: JSON.stringify(this.article),
                    dataType: 'json',
                    success: function(ret) {
                        if (ret.code == 0) {
                            ret.data.createTime = new Date(parseInt(ret.data.createTime)).toLocaleString().replace(/:\d{1,2}$/, ' ');
                            wrapper.resetArticle();
                            Messenger.options = {
                                extraClasses: 'messenger-fixed messenger-on-bottom messenger-on-right',
                                theme: 'block'
                            }
                            Messenger().post({
                                message: '保存成功.',
                                type: 'success',
                                showCloseButton: true

                            })

                        } else {
                            errorPrecess(ret);
                        }
                    },
                    error: function(XMLHttpRequest, textStatus, errorthrow) {
                        alert("XMLHttpRequest.status=" + XMLHttpRequest.status);
                    }
                });
            },
            resetArticle: function() {
                wrapper.$set(wrapper.article, "id", "0");
                wrapper.$set(wrapper.article, "title", '');
                wrapper.$set(wrapper.article, "headImg", '');
                wrapper.$set(wrapper.article, "content", '');
                wrapper.$set(wrapper.article, "type", '');
                wrapper.$set(wrapper.article, "mediaId", '');



                UE.getEditor('myEditor').setContent('');

            },
            resetArticle2: function() {
                var msg = "确定要重置文章吗？";
                if (confirm(msg) == true) {
                    this.resetArticle();

                } else {
                    return;
                }



            },
            getArticleDetail: function(articleId) {
                $.ajax({
                    type: "GET",
                    url: "../article/getNewsDetail?id=" + articleId,
                    dataType: "json",
                    success: function(ret) {
                        console.log(ret);
                        if (ret.code == 0) {
                            wrapper.$set(wrapper.article, "id", ret.data.id);
                            wrapper.$set(wrapper.article,"title",ret.data.title);
                            wrapper.$set(wrapper.article, "headImg", ret.data.headImg);
                            wrapper.$set(wrapper.article,"content",ret.data.content); 
                            // wrapper.$set(wrapper.article, "type", ret.data.type);
                            wrapper.$set(wrapper.article, "mediaId", ret.data.mediaId);
                            ueditorContent=ret.data.content;
                            //页面初始化试赋值会报错  要等uedit加载好才可以赋值
                             // UE.getEditor('myEditor').setContent(bigbox.article.content);
                                
                                 
                        } else {
                            errorPrecess(ret);
                        }
                    }
                });


            }

        }
    })
    articleId = getUrlParam('articleId')
    if (articleId != null) {
        // bigbox.show=true;
        wrapper.getArticleDetail(articleId);
        ue.ready(function() { //编辑器初始化完成再赋值  
            ue.setContent(ueditorContent);
        });

    }
    $(".sidebar-menu li").removeClass('active');
    $(".sidebar-menu li:nth-child(3)").addClass('active');


})
